local vector2d = require("Vector2D")

M = {}

local maxVelocityPlanet = 180 
local gravity_constant = 16000
--density = 0.4

local function dist(object1,object2)
    return  math.sqrt((object1.x - object2.x)^2 + (object1.y - object2.y)^2 )
end

local function gravity(player,planet,inPlanet)
    local vp = vector2d:new(player.x, player.y)
    local vi = vector2d:new(planet.x, planet.y)
    vi:sub(vp)
    local magnitud = vi:magnitude()
    vi:normalize()
    local mag2 = magnitud * magnitud
    local fuerza = gravity_constant *  planet.gravity/ mag2
    --print(inPlanet)
    if(inPlanet)then
        local inPlanetF = 6 *(planet.radio + player.radio)^2  / magnitud^2
        --print(inPlanetF)
        vi:mult(inPlanetF)
        if(player.planet==nil)then
            local vp = vector2d:new(player:getLinearVelocity())            
            player:setLinearVelocity( vp.x * 0.99, vp.y * 0.99 );
        end
        
    else
        vi:mult(fuerza)
        --print("OUT:"..fuerza)
    end
    player:applyForce(vi.x, vi.y, player.x, player.y)
end


local applyGravity = function(player, game)
    --culling for planets
    local inPlanets = {}
    local j= 1
    local planetGroup = game[2]
    for i = 1, planetGroup.numChildren do
        local magnitud = dist(planetGroup[i],player)
        if(magnitud < planetGroup[i].radio + planetGroup[i].atmosfera + player.radio)then
            --print("in")
            inPlanets[j]= planetGroup[i]
            j = j + 1
        end
        
    end
    
    if (player.planeta == nil) then        
        if(#inPlanets>0)then
            --print("inplanet")
            for i = 1, #inPlanets do
                gravity(player,inPlanets[i],true)
                
            end
        else  
            --print("outplanet")
            for i = 1, planetGroup.numChildren do
                gravity(player,planetGroup[i],false)
                
            end
        end
        --print("vuela")
    else
        gravity(player,player.planeta,true)
        --print("planeta")
    end
    
    
end

M.applyGravity = applyGravity

local jump = function(player)
    local vp = vector2d:new(player.x, player.y)
    local vi = vector2d:new(player.planeta.x, player.planeta.y)
    vp:sub(vi)
    vp:normalize()
    player:applyLinearImpulse(vp.x * 1.3, vp.y * 1.3, player.x, player.y)
end

M.jump = jump

local speed = function(player)
    --velocidad en planeta
    local vp = vector2d:new(player:getLinearVelocity())
    if (player.planeta ~= nil and vp:magnitude() == 0) then
        player:applyForce( 0.1, 0.1, player.x, player.y );
    elseif (player.planeta ~= nil and vp:magnitude() < maxVelocityPlanet) then
        player:setLinearVelocity( vp.x * 1.05, vp.y * 1.05 );
    end
    --no necesito limitar velocidad
    --[[
    elseif (vp:magnitude() > (maxVelocityPlanet * 4)) then
        player:setLinearVelocity( vp.x * 0.9, vp.y * 0.9 );
    end
    --]]
end

M.speed = speed

return M
